Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Is it possible to "initialize" a React component?

So basically I'm trying to implement a restart function for my game, and I would like to be able to somehow "reload" my GameView component. Here's the lifecycle: 1. React renders/mounts my component 2. user interacts with the component and it changes 3. now, I want to call a function to basically wipe off all those changes and bring the component (and all of its child) back to its state in step 1. Here are 2 possible solutions I've thought of:

  • keep the same component and set all the state variables back to their initialized values
  • make a new component and replace the old one

The first is not very practical since it gets very complicated when child components gets involved and the second doesn't work because apparently React still views the new component as being identical the old one since they have the same props? I'm not sure why but I couldn't get it to work.

I would greatly appreciate some help!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a key to force react to unmount and remount the component. Keys give react additional information about which element from one render corresponds to which element from the next render. If the keys are different, then this tells react they are different elements, even if they have the same type.

const App = () => {
  const [gameNumber, setGameNumber] = useState();

  const resetGameView = () => {
    setGameNumber(prev => prev + 1);
  }

  return (
    <div>
      <GameView key={gameNumber} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda